package mongodb

import (
	"context"
	"github.com/Sir-yuChen/funAnalyse/global"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"go.uber.org/zap"
	"time"
)

const (
	defaultTimeout = 50 * time.Second
	maxPoolSize    = 10
)

func InitMongoDB() error {
	url := "mongodb://" + global.GVA_CONFIG.MongoDB.Link
	ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
	defer cancel()
	var poolSize int
	if global.GVA_CONFIG.MongoDB.MaxPoolSize > 0 {
		poolSize = global.GVA_CONFIG.MongoDB.MaxPoolSize
	} else {
		poolSize = maxPoolSize
	}
	// 设置客户端连接配置 连接到MongoDB
	MongoClient, err := mongo.Connect(ctx,
		options.Client().ApplyURI(url).
			SetMaxPoolSize(uint64(poolSize)), /*.
		SetAuth(options.Credential{ // 设置验证参数
			Username: "root",     // 用户名
			Password: "123456"}), // 密码*/
	)
	if err != nil {
		global.GVA_LOG.Error("", zap.Any("MongoDB连接异常", url), zap.Error(err))
		return err
	}
	// 检查连接
	if err = MongoClient.Ping(ctx, readpref.Primary()); err != nil {
		global.GVA_LOG.Error("", zap.Any("MongoDB检查连接异常", url), zap.Error(err))
		return err
	}
	//全局参数
	global.GVA_MongoDB = MongoClient
	return nil
}
